<?php
/**
 * GeoContexter
 * @link http://code.google.com/p/geocontexter/
 * @package GeoContexter
 */

/**
 * Main setup action controller
 *
 * @package GeoContexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Setup\Controller;

use Zend\View\Model\ViewModel;
use Core\Controller\Abstract2Controller;

class IndexController extends Abstract2Controller
{
    private $error = array();

    public $local_config = array('adminAreaToken' => 'sec_secret',
                                 'error_handling' => 0,
                                 'production_error_message' => 'An unexpected error occurred. Please contact the admin.'
                                );

    /**
     * init the controller
     *
     * executed before any action logic
     */
    public function init()
    {
        $this->initView( 'setup/index/index.phtml', true );
        $this->view->basePath = $this->getRequest()->getBasePath();
    }

    public function indexAction()
    {

        $this->view->timezone_identifiers = \DateTimeZone::listIdentifiers();
        $this->error                      = array();
        $this->__error                    =  false;
        $data                             = array();

        if (version_compare(PHP_VERSION, '5.3') == -1) {
            $this->error[] = "PHP version 5.3 or greather required. Your version is: " . PHP_VERSION;
        }

        $this->check_files_and_folders();

        // fetch form content
        //
        $this->get_view_vars();

        if ((count($this->error == 0)) && $this->request->getPost()->do_setup) {

            try {
                // try to connect to the db server
                //
                $data['db'] = new \PDO('pgsql:host='.$this->getRequest()->getPost('dbhost').';dbname='.$this->getRequest()->getPost('dbname'),
                                       $this->getRequest()->getPost('dbuser'),
                                       $this->getRequest()->getPost('dbpasswd') );

                //$this->check_postgis_version($data['db']);

                $this->check_namespace_serial( $data );

                $data['version'] = '1.0';

                $insert_sample_content = $this->request->getPost()->insertsamplecontent;

                // if insert sample test content we force namespace, srid and serial
                //
                if (null !== $insert_sample_content) {
                    $data['namespace'] = 'test';
                    $data['srid']      = '4326';
                    $data['serial']    = '1';
                } else {
                    $data['srid']    = trim($this->request->getPost()->srid);

                    if (preg_match("/[^0-9]/",$data['srid'])) {
                        $this->error[] = 'Spatial reference system identifier (SRID) must be number';
                    }
                }

                $data['superuser_login']    = trim($this->request->getPost()->superuserlogin);
                $data['superuser_password'] = $this->request->getPost()->superuserpassword;
                $data['superuser_timezone'] = $this->request->getPost()->superusertimezone;

                if (empty($data['superuser_login'])) {
                    $this->error[] = 'Super user login name is empty';
                }

                if (empty($data['superuser_password'])) {
                    $this->error[] = 'Super user password is empty';
                }

                if (count($this->error) > 0) {
                    $this->view->error = $this->error;
                    return $this->view;
                }

                // write db connection vars in local.php file
                //

				$this->local_config['service_manager']   = array(
					'factories' => array(
						'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
					),
					'aliases' => array(
						'db' => 'Zend\Db\Adapter\Adapter',
					),
				);

                $this->local_config['db']['driver']   = "pdo_pgsql";
                $this->local_config['db']['schema']   = "geocontexter";
                $this->local_config['db']['host']     = $this->request->getPost()->dbhost;
                $this->local_config['db']['username'] = $this->request->getPost()->dbuser;
                $this->local_config['db']['password'] = $this->request->getPost()->dbpasswd;
                $this->local_config['db']['dbname']   = $this->request->getPost()->dbname;
                $this->local_config['db']['charset']  = 'utf8';

                $writer = new \Zend\Config\Writer\PhpArray();
                $writer->toFile(GEOCONTEXTER_ROOT . '/config/autoload/local.php', $this->local_config);

                $RunSqlSetupFile = $this->CoreModel('RunSqlSetupFile', 'Setup');
                $RunSqlSetupFile->run( $data );

                //insert sample test content
                if (null !== $insert_sample_content) {
                    $InsertSampleContent = $this->CoreModel('InsertSampleContent', 'Setup');
                    $InsertSampleContent->run( $data );
                }

                return $this->redirect()->toUrl($this->getRequest()->getBasePath() . '/sec_secret/login');

            } catch (\PDOException $e) {
                $this->error[] = $e->getMessage();
            } catch (\Exception $e) {
                $this->error[] = $e->getMessage();
            }
        }

        $this->view->error = $this->error;

        return $this->view;
    }

    private function check_namespace_serial( & $data )
    {
        $namespace = trim($this->request->getPost()->namespace);

        if ($namespace == 'namespace') {
            $data['namespace'] = trim($this->request->getPost()->namespace_value);
        } else {
            $data['namespace'] = $this->request->getPost()->namespace;
        }

        if (preg_match("/[^a-zA-Z0-9_-]/",$data['namespace']))  {
            $this->error[] = 'Namespace only acccept the following chars "a-zA-Z0-9_-"';
        }

        if ($data['namespace'] == 'test') {
            $data['serial'] = '9223';
        }

        if ($data['namespace'] == 'standalone') {
            $data['serial'] = '1';
        }

        $data['serial']    = trim($this->request->getPost()->serial);

        if (preg_match("/[^0-9-]/",$data['serial'])) {
            $this->error[] = 'System serial must be number between -9222 and 9222, except 0';
        }

        if (((int)$data['serial'] < -9222) || ((int)$data['serial'] > 9223) || ((int)$data['serial'] == 0)) {
            $this->error[] = 'System serial must be number between -9222 and 9222';
        }
    }

    private function get_db_connection() {
        return new \PDO('pgsql:host='.$this->request->getPost()->dbhost.';dbname='.$this->request->getPost()->dbname,
                        $this->request->getPost()->dbuser,
                        $this->request->getPost()->dbpasswd );
    }

    private function check_postgis_version($db)
    {
        if ($result = $db->query('SELECT postgis_full_version()')) {
            $row = $result->fetch();
        } else {
            $this->error[] = "Geocontexter require postgis extension of postgresql";
        }
    }

    private function check_files_and_folders()
    {
        if (!is_writeable(GEOCONTEXTER_ROOT . "/config/autoload")) {
            $this->error[] = "Folder must be writeable: " . APPLICATION_PATH . "/configs";
        }

        if (!is_writeable(GEOCONTEXTER_ROOT . "/public/data")) {
            $this->error[] = "Folder must be writeable: /public/data";
        }

        if (!is_writeable(GEOCONTEXTER_ROOT . "/public/data/gc_item")) {
            $this->error[] = "Folder must be writeable: /public/data/gc_item";
        }

        if (!is_writeable(GEOCONTEXTER_ROOT . "/public/data/gc_record")) {
            $this->error[] = "Folder must be writeable: /public/data/gc_record";
        }

        if (!is_writeable(GEOCONTEXTER_ROOT . "/public/data/export")) {
            $this->error[] = "Folder must be writeable: /public/data/export";
        }

        if (!is_writeable(GEOCONTEXTER_ROOT . "/module/Geocontexter/tmp")) {
            $this->error[] = "Folder must be writeable: /modules/geocontexter/tmp";
        }
    }

    private function get_view_vars()
    {
        $this->view->form_dbhost      = trim($this->request->getPost()->dbhost);
        $this->view->form_dbport      = trim($this->request->getPost()->dbport);
        $this->view->form_dbuser      = trim($this->request->getPost()->dbuser);
        $this->view->form_dbpasswd    = trim($this->request->getPost()->dbpasswd);
        $this->view->form_dbname      = trim($this->request->getPost()->dbname);
        $this->view->form_superuser_login    = trim($this->request->getPost()->superuserlogin);
        $this->view->form_superuser_password = trim($this->request->getPost()->superuserpassword);
        $this->view->form_superuser_timezone = $this->request->getPost()->superusertimezone;
        $this->view->form_srid               = $this->request->getPost()->srid;
        $this->view->form_namespace          = $this->request->getPost()->namespace;
        $this->view->form_namespace_value    = $this->request->getPost()->namespace_value;

        if (empty($this->view->form_namespace)) {
            $this->view->form_namespace = "test";
        }

        $this->view->form_serial = trim($this->request->getPost()->serial);
    }
}

